package com.lalifa.googledate.ui.activity

import android.annotation.SuppressLint
import android.app.AlarmManager
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import androidx.core.view.isVisible
import com.blankj.utilcode.util.ActivityUtils
import com.drake.net.utils.scopeNetLife
import com.lalifa.base.BaseActivity
import com.lalifa.ext.showInputDialog
import com.lalifa.extension.PATTERN_DATE
import com.lalifa.extension.PATTERN_FULL
import com.lalifa.extension.PATTERN_HOUR_MINUTE
import com.lalifa.extension.TouchListener
import com.lalifa.extension.format
import com.lalifa.extension.getIntentSerializable
import com.lalifa.extension.gone
import com.lalifa.extension.hideKeyboard
import com.lalifa.extension.onClick
import com.lalifa.extension.text
import com.lalifa.extension.toTime
import com.lalifa.extension.toast
import com.lalifa.extension.visible
import com.lalifa.extension.warData
import com.lalifa.googledate.R
import com.lalifa.googledate.api.ChooseTimeBean
import com.lalifa.googledate.api.EventListBean
import com.lalifa.googledate.api.HolidayUp
import com.lalifa.googledate.api.RemindBean
import com.lalifa.googledate.api.addEventApi
import com.lalifa.googledate.databinding.ActivityAddBinding
import com.lalifa.googledate.ui.adapter.ArrayWheelAdapter
import com.lalifa.googledate.ui.adapter.addNoticeAdapter
import com.lalifa.googledate.ui.dialog.chooseCalendarDialog
import com.lalifa.googledate.ui.dialog.showChooseTimeDialog
import com.lalifa.googledate.ui.dialog.showColorDialog
import com.lalifa.googledate.ui.dialog.showResumeDialog
import com.lalifa.googledate.util.CalendarUtils
import com.lalifa.googledate.util.CalendarUtils.upEvent
import com.lalifa.googledate.util.Tool
import com.lalifa.googledate.util.UserManager
import com.lalifa.googledate.util.createNotificationChannel
import com.lalifa.googledate.util.launchActivityIntent
import com.lalifa.googledate.util.sendNotificationWithSoundAndVibration
import com.lalifa.googledate.util.showNotificationLayer
import com.lalifa.utils.LiveDataBus
import com.lalifa.utils.UIKit
import java.util.regex.Pattern

class AddActivity : BaseActivity<ActivityAddBinding>() {
    override fun getViewBinding() = ActivityAddBinding.inflate(layoutInflater)
    var id = CalendarUtils.CALENDARS_Id
    var description = ""
    var location = ""
    var color = Color.parseColor(Tool.color)
    var isAllDay = "0"
    var mRepeatRule = 0
    val arr1 = arrayListOf<ChooseTimeBean>()
    val arr2 = arrayListOf<ChooseTimeBean>()
    var before = ""
    var other = ""
    var choose = 1
    var list1 = arrayListOf<String>()
    var list2 = listOf<String>()
    var list22 = listOf<String>()
    var list3 = listOf<String>()
    var eventId = -1L

    @SuppressLint("ClickableViewAccessibility")
    override fun initView() {
        val bean = getIntentSerializable<EventListBean>("EventListBean")
        if (bean != null) {
            val event = bean.event
            binding.apply {
                eventId = event.id.toLong()
                etTitle.setText(event.title)
                openAllDay.isSelected = event.isallday
                isAllDay = if (openAllDay.isSelected) "1" else "0"
                time3.isVisible = !openAllDay.isSelected
                time4.isVisible = !openAllDay.isSelected
                time1.text = event.starttime.format(PATTERN_DATE)
                time2.text = event.starttime.format(PATTERN_DATE)
                time3.text = event.starttime.format(PATTERN_HOUR_MINUTE)
                time4.text = event.starttime.format(PATTERN_HOUR_MINUTE)
                dw.text = event.address
                location = event.address
                id = event.accountId
                set1.leftText = event.accountname
                color = event.eventcolor
                showColor.setBackgroundColor(event.eventcolor)
                set3.leftText = event.info
            }
        }
        before = getString(R.string.before)
        other = getString(R.string.add_other_notify)
        list1 = arrayListOf(getString(R.string.am), getString(R.string.pm))
        list2 = resources.getStringArray(R.array.hour_list).toList()
        list22 = resources.getStringArray(R.array.hour_list2).toList()
        list3 = resources.getStringArray(R.array.minute_list).toList()
        arr2.add(ChooseTimeBean("5 minutes$before", 5))
        arr2.add(ChooseTimeBean("10 minutes$before", 10))
        arr2.add(ChooseTimeBean("15 minutes$before", 15))
        arr2.add(ChooseTimeBean("30 minutes$before", 30))
        arr2.add(ChooseTimeBean("1 hours$before", 60))
        arr2.add(ChooseTimeBean("1 days$before", 60 * 24))
        arr1.add(
            ChooseTimeBean(
                other, 0, isShow =
                true
            )
        )
        binding.apply {
            set1.leftText = UserManager.get()!!.email.pk()
            tzList.addNoticeAdapter().apply {
                R.id.remove.onClick {
                    arr1.remove(getModel())
                    arr2.add(getModel())
                    arr2.sortBy { it.time }
                    models = arr1
                }
                R.id.tvTime.onClick {
                    if (getModel<ChooseTimeBean>().time == 0) {
                        showChooseTimeDialog(arr2) { backItem ->
                            arr1.add(models!!.size - 1, backItem)
                            arr2.remove(backItem)
                            models = arr1
                        }
                    }
                }
            }.models = arr1
            wheel1.setOnTouchListener(TouchListener())
            wheel2.setOnTouchListener(TouchListener())
            wheel3.setOnTouchListener(TouchListener())
            wheel1.setCyclic(false)
            wheel2.setCyclic(false)
            wheel3.setCyclic(false)
            val adapter1 = ArrayWheelAdapter<Any?>(list1.toList())
            val adapter2 = ArrayWheelAdapter<Any?>(list2.toList())
            val adapter22 = ArrayWheelAdapter<Any?>(list22.toList())
            val adapter3 = ArrayWheelAdapter<Any?>(list3.toList())
            wheel1.adapter = adapter1
            wheel2.adapter = adapter2
            wheel3.adapter = adapter3
            wheel1.setOnItemSelectedListener {
                when (it) {
                    0 -> wheel2.adapter = adapter2
                    1 -> wheel2.adapter = adapter22
                }
            }
            val now = System.currentTimeMillis()
            time1.text = now.format(PATTERN_DATE)
            time2.text = now.format(PATTERN_DATE)
            time3.text = now.format(PATTERN_HOUR_MINUTE)
            time4.text = now.format(PATTERN_HOUR_MINUTE)
            calenderPop.date = now
            calenderPop.gone()
            calenderPop.setOnDateChangeListener { _, year, month, day ->
                val m = if (month + 1 < 10) "0${month + 1}" else "$month"
                val d = if (day < 10) "0$day" else "$day"
                if (choose == 1) {
                    time1.text = "$year-$m-$d"
                } else {
                    val s = "$year-$m-$d"
                    if (time1.text.toString().warData(s, PATTERN_DATE) == -1) {
                        toast(getString(R.string.start_before_end))
                    } else {
                        time2.text = s
                    }
                }
                time2.visible()
                if (isAllDay != "1") {
                    time4.visible()
                }
                calenderPop.gone()
            }
        }
    }

    @SuppressLint("DiscouragedApi", "UseCompatLoadingForDrawables", "SetTextI18n")
    override fun onClick() {
        super.onClick()
        binding.apply {
            back.onClick { finish() }
            dw.onClick {
                showInputDialog(getString(R.string.add_address), l = 80) {
                    dw.text = it
                    location = it
                }
            }
            toMap.onClick {
                showOnMap()
            }
            set1.onClick {
                hideKeyboard(set1)
                chooseCalendarDialog(CalendarUtils.CALENDARS_LIST) {
                    set1.leftText = it.name
                    id = it.id
                    if (it.icon.isNotEmpty()) {
                        val resources = UIKit.getResources()
                        try {
                            val resourceId: Int =
                                resources.getIdentifier(it.icon, "drawable", packageName)
                            if (resourceId != 0) {
                                set1.leftDrawable = resources.getDrawable(resourceId)
                            }
                        } catch (e: Exception) {

                        }
                    }

                }
            }
            openAllDay.onClick {
                openAllDay.isSelected = !openAllDay.isSelected
                isAllDay = if (openAllDay.isSelected) "1" else "0"
                time3.isVisible = !openAllDay.isSelected
                time4.isVisible = !openAllDay.isSelected
            }
            getTime.onClick {
                if (choose == 1) {
                    if (wheel1.currentItem == 0) {
                        time3.text = "${list2[wheel2.currentItem]}:${list3[wheel3.currentItem]}"
                    } else {
                        time3.text =
                            "${list22[wheel2.currentItem].toInt()}:${list3[wheel3.currentItem]}"
                    }
                    timePop.gone()
                    time2.visible()
                    time4.visible()
                } else {
                    var s = ""
                    s = if (wheel1.currentItem == 0) {
                        "${list2[wheel2.currentItem]}:${list3[wheel3.currentItem]}"
                    } else {
                        "${list22[wheel2.currentItem].toInt()}:${list3[wheel3.currentItem]}"
                    }
                    if (time1.text.toString().warData(time2.text.toString(), PATTERN_DATE) == 0) {
                        if (time3.text.toString().warData(s, PATTERN_HOUR_MINUTE) == -1) {
                            toast(getString(R.string.start_before_end))
                        } else {
                            time4.text = s
                            timePop.gone()
                        }
                    } else {
                        time4.text = s
                        timePop.gone()
                    }
                }
            }
            time1.onClick {
                choose = 1
                timePop.gone()
                calenderPop.isVisible = !calenderPop.isVisible
                time2.isVisible = !calenderPop.isVisible
                time4.isVisible = !calenderPop.isVisible
            }
            time2.onClick {
                timePop.gone()
                choose = 2
                calenderPop.isVisible = !calenderPop.isVisible
            }
            time3.onClick {
                choose = 1
                calenderPop.gone()
                timePop.isVisible = !timePop.isVisible
                time2.isVisible = !timePop.isVisible
                time4.isVisible = !timePop.isVisible
                nest.isNestedScrollingEnabled = !timePop.isVisible
            }
            time4.onClick {
                choose = 2
                calenderPop.gone()
                time2.visible()
                timePop.isVisible = !timePop.isVisible
                nest.isNestedScrollingEnabled = !timePop.isVisible
            }
            set3.onClick {
                showInputDialog(l = 800) {
                    description = it
                    set3.leftText = it
                }
            }
            set2.onClick {
                showColorDialog() {
                    color = Color.parseColor(it.value)
                    showColor.setBackgroundColor(color)
                    set2.leftText = it.name
                }
            }
            cf.onClick {
                showResumeDialog {

                }
            }
            sure.onClick {
                val t = etTitle.text()
                if (t.isEmpty()) {
                    etTitle.requestFocus()
                    toast(getString(R.string.place_input_event_title))
                    return@onClick
                }
                hideKeyboard(sure)
                val m = arrayListOf<Int>()
                if (arr1.isNotEmpty()) {
                    arr1.forEach {
                        m.add(it.time)
                    }
                }
                val start = time1.text.toString() + " " + time3.text.toString() + ":00"
                val end = time2.text.toString() + " " + time4.text.toString() + ":00"
                val toTime = start.toTime(PATTERN_FULL)
                val toTime1 = end.toTime(PATTERN_FULL)
                if (toTime > toTime1) {
                    toast(getString(R.string.start_before_end))
                    return@onClick
                }
                getProgress(this@AddActivity)
                if (eventId != -1L) {
                    upEvent(
                        eventId, t,
                        description,
                        location,
                        color,
                        start.toTime(PATTERN_FULL),
                        end.toTime(PATTERN_FULL),
                        isAllDay, m, id
                    ) {
                        if (it) {
                            LiveDataBus.get().with("holidayList").value = HolidayUp(-1)
                            hindProgress()
                            finish()
                        } else {
                            toast(getString(R.string.add_err))
                            hindProgress()
                        }
                    }
                } else {
//                    scopeNetLife {
//                        addEventApi(
//                            UserManager.get()!!.idToken.pk(),
//                            t,
//                            start,
//                            end,
//                            "Asia/Shanghai",
//                            "不重复",
//                            "即时提醒",
//                            location,
//                            description
//                        )
//                    }
                    val isOk = CalendarUtils.addCalendarEvent(
                        this@AddActivity, t,
                        description,
                        location,
                        color,
                        start.toTime(PATTERN_FULL),
                        end.toTime(PATTERN_FULL),
                        isAllDay, m, id
                    )
                    if (isOk) {
                        LiveDataBus.get().with("holidayList").value = HolidayUp(-1)
//                        createNotificationChannel()
//                        sendNotificationWithSoundAndVibration(
//                            id.toString(), t, description
//                        )
//                        val bean = RemindBean("$id", start.toTime(PATTERN_FULL), t, description)
//                        ActivityUtils.getTopActivity().showNotificationLayer(bean)

                        hindProgress()
                        finish()
                    } else {
                        toast(getString(R.string.add_err))
                        hindProgress()
                    }
                }
            }
        }
    }

    private val LAT_LON_PATTERN = "^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)([,;])\\s*[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)\$"
    private fun showOnMap() {
        if (binding.dw.text.isEmpty()) {
            toast(R.string.place_input_name)
            return
        }

        val pattern = Pattern.compile(LAT_LON_PATTERN)
        val locationValue = binding.dw.text.toString()
        val uri = if (pattern.matcher(locationValue).find()) {
            val delimiter = if (locationValue.contains(';')) ";" else ","
            val parts = locationValue.split(delimiter)
            val latitude = parts.first()
            val longitude = parts.last()
            Uri.parse("geo:$latitude,$longitude")
        } else {
            val location = Uri.encode(locationValue)
            Uri.parse("geo:0,0?q=$location")
        }

        val intent = Intent(Intent.ACTION_VIEW, uri)
        launchActivityIntent(intent)
    }
}